package com.jse.security.simple;

import org.junit.Test;
import sun.misc.BASE64Encoder;

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;

/**
 * @author : zenghua
 * @version : v0.1 PRPair.java
 * @since : 2017/7/10 15:15
 */
public class PRPair {

    /**
     * 生成公/私钥对
     * 参考：http://docs.oracle.com/javase/7/docs/technotes/guides/security/StandardNames.html#KeyPairGenerator
     */
    @Test
    public void testPublicKey() {
        KeyPairGenerator keyPairGenerator;
        try {
            keyPairGenerator = KeyPairGenerator.getInstance("RSA");
            keyPairGenerator.initialize(1024);
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalArgumentException("不支持的算法名称");
        }

        KeyPair keyPair = keyPairGenerator.generateKeyPair();
        RSAPublicKey rsaPublicKey = (RSAPublicKey)keyPair.getPublic();
        RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyPair.getPrivate();

        BASE64Encoder base64Encoder = new BASE64Encoder();
        String encodePublicKey = base64Encoder.encodeBuffer(rsaPublicKey.getEncoded());
        System.out.println("BASE64后的公钥：" + encodePublicKey);
        String encodePrivateKey = base64Encoder.encodeBuffer(rsaPrivateKey.getEncoded());
        System.out.println("BASE64后的密钥：" + encodePrivateKey);

//        System.out.println((new BASE64Encoder()).encodeBuffer(rsaPublicKey.getEncoded()));
    }
}
